<?php

include 'def.php';

$tables = array('teacher','student','class','enrollment');

$json_array = array('status'=>'error','error_id'=>'input','error_description'=>'request data error');

session_start();

if( !isset($_GET['token']) || !isset($_GET['type']) )
{/* do nothing */	
}
elseif( /*session_id()!=$_GET['token'] || */ empty($_GET['type']) )
{/*do nothing*/
}
else{
	$table = $_GET['type'];
	
	if( !in_array( $table, $tables ) )
	{/* do nothing */
		$json_array = array('status'=>'error', "error_id"=>"$table",'error_description'=>'unknown type');	
	}
	else{
		$conn = mysql_connect(DBSERV, DBUSER, DBPASSWD) or die("Couldn't connect to database");
		
		$db = mysql_select_db(DB) or die("Couldn't connect to database");
		
		$query = "select * from $table";
		
		if( isset($_GET['id']) and isset($_GET['timestamp']) )
		{
			$id = $_GET['id'];
			$timestamp = $_GET['timestamp'];
			$query .= " where {$table}ID = '$id' and $timestamp < unix_timestamp(lastupdate)";
		}
		elseif( isset($_GET['id']) )
		{
			$id = $_GET['id'];
			$query .= " where {$table}ID = '$id'";
		}
		elseif( isset($_GET['timestamp']) )
		{
			$timestamp = $_GET['timestamp'];
			$query .= " where $timestamp < unix_timestamp(lastupdate)";
		}
			
		$result = mysql_query($query) or die('Query_failed: ' . mysql_error());

		$data = array();
		while( $row = mysql_fetch_assoc($result) )
		{
			$row['timestamp']=strtotime($row['lastupdate']);
			$data[] = $row;
		}
		
		$json_array = array( 'status'=>'OK', 'data'=>$data );
		}
}		

echo (json_encode($json_array));
?>